import * as ModelProto from '@/proto/model/ModelProto'
import messageBus from '@/utils/MessageBus'
import {Command} from '@/const/Constants'
import { useState } from 'react'
//定义ws服务对象
class WebSocketClient {
  private webSocket: WebSocket | null = null

  private url: string

  //是否认证
  public isAuthorized: boolean = false

  constructor(url: string) {
    this.url = url
  }

  connect(request: ModelProto.Request) {
    if (this.webSocket && this.webSocket.readyState === WebSocket.OPEN) {
      console.log('WebSocket is already connected.')
      return
    }
    this.webSocket = new WebSocket(this.url)
    this.webSocket.binaryType = 'arraybuffer'

    this.webSocket.onopen = () => {
      console.log('WebSocket connected')

      //连接成功后发送认证信息
      this.sendMessage(request)
    }

    this.webSocket.onmessage = (event) => {
      const buffer = new Uint8Array(event.data)
      let response = ModelProto.Response.decode(buffer)
      if (response) {
        messageBus.dispatch(response)
      }

      console.log('Message from server ', response)
    }

    this.webSocket.onerror = (error) => {
      console.error('WebSocket error: ', error)
    }

    this.webSocket.onclose = () => {
      console.log('WebSocket disconnected')
    }
  }

  disconnect() {
    if (this.webSocket) {
      this.webSocket.close()
      this.webSocket = null
    }
  }

  sendMessage(message: ModelProto.Request) {
    if (this.webSocket && this.webSocket.readyState === WebSocket.OPEN) {
      if (message.header?.command == Command.AUTH || this.isAuthorized) {
        this.webSocket.send(ModelProto.Request.encode(message).finish())
        return;
      }

      console.error('WebSocket is not Authorized.')
    } else {
      console.error('WebSocket is not connected.')
    }
  }

  setIsAuthorized(value: boolean) {
    this.isAuthorized = value
  }
}

const websocketClient = new WebSocketClient('ws://localhost:6501')

export default websocketClient
